<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">用户登录</div>
    <div class="login-form-sub-title">客户端平台</div>
    <div class="login-form-error-msg">{{ errorMessage }}</div>
    <a-form
      ref="loginForm"
      :model="userInfo"
      class="login-form"
      layout="vertical"
      @submit="handleSubmit"
    >
      <a-form-item
        v-if="!userInfo.tenantCode"
        field="tenantCode"
        :rules="[{ required: true, message: '租户编码不能为空' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input v-model="userInfo.tenantCode" placeholder="请输入租户编码">
          <template #prefix>
            <icon-building-one />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        field="username"
        :rules="[{ required: true, message: '用户名不能为空' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input v-model="userInfo.username" placeholder="请输入用户名">
          <template #prefix>
            <icon-user />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        field="password"
        :rules="[{ required: true, message: '密码不能为空' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input-password
          v-model="userInfo.password"
          placeholder="请输入密码"
          allow-clear
        >
          <template #prefix>
            <icon-lock />
          </template>
        </a-input-password>
      </a-form-item>

      <a-form-item
        field="captcha"
        :rules="[{ required: true, message: '验证码不能为空' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input
          v-model="userInfo.captcha"
          placeholder="请输入验证码"
          allow-clear
        >
          <template #prefix>
            <icon-safe />
          </template>
          <template #append>
            <img
              v-if="captcha.image"
              class="captcha"
              :src="`data:image/png;base64,${captcha.image}`"
              alt="验证码"
              @click="fetchCaptcha"
            />
          </template>
        </a-input>
      </a-form-item>
      <a-space :size="16" direction="vertical">
        <div class="login-form-password-actions">
          <a-checkbox
            checked="rememberPassword"
            :model-value="loginConfig.rememberPassword"
            @change="setRememberPassword as any"
          >
            {{ $t('login.form.rememberPassword') }}
          </a-checkbox>
          <a-link>{{ $t('login.form.forgetPassword') }}</a-link>
        </div>
        <a-button type="primary" html-type="submit" long :loading="loading">
          {{ loginButtonLabel }}
        </a-button>
      </a-space>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
  import { Message } from '@arco-design/web-vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import { useStorage } from '@vueuse/core';
  import { ref, reactive } from 'vue';
  import { useRouter } from 'vue-router';

  import { getCaptchaApi, getTenantCodeApi } from '@/api/system/authorization';
  import type { LoginData } from '@/api/system/authorization/types';
  import useLoading from '@/hooks/loading';
  import { DEFAULT_ROUTE_NAME } from '@/router/constants';
  import { useUserStore } from '@/store';

  const router = useRouter();
  const userStore = useUserStore();
  const { loading, setLoading } = useLoading();
  const captcha = ref<any>({});
  const loginButtonLabel = ref('登录');
  const errorMessage = ref('');

  const loginConfig = useStorage('login-config', {
    rememberPassword: true,
    username: '',
    password: '',
  });

  const userInfo = reactive({
    tenantCode: '',
    username: loginConfig.value.username,
    password: loginConfig.value.password,
    captcha: '',
  });

  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (loading.value) return;
    if (!errors) {
      setLoading(true);
      try {
        await userStore.login({
          ...(values as LoginData),
          uuid: captcha.value?.id,
        });
        loginButtonLabel.value = '页面加载中，请稍后...';
        const { redirect, ...othersQuery } = router.currentRoute.value.query;
        await router.push({
          name: (redirect as string) || DEFAULT_ROUTE_NAME,
          query: {
            ...othersQuery,
          },
        });
        Message.success('登录成功，欢迎使用。');
        const { rememberPassword } = loginConfig.value;
        const { username, password } = values;
        // 实际生产环境需要进行加密存储。
        loginConfig.value.username = rememberPassword ? username : '';
        loginConfig.value.password = rememberPassword ? password : '';
      } catch (err) {
        loginButtonLabel.value = '登录';
        errorMessage.value = (err as Error).message;
        fetchCaptcha();
      } finally {
        setLoading(false);
      }
    }
  };

  const setRememberPassword = (value: boolean) => {
    loginConfig.value.rememberPassword = value;
  };

  const fetchTenantCode = () => {
    const domain = window.location.hostname;
    getTenantCodeApi(domain).then((res: any) => {
      userInfo.tenantCode = res || '';
    });
  };

  const fetchCaptcha = () => {
    getCaptchaApi().then((res: any) => {
      captcha.value = res;
    });
  };

  onMounted(() => {
    fetchTenantCode();
    fetchCaptcha();
  });
</script>

<style lang="less" scoped>
  .login-form {
    &-wrapper {
      width: 320px;
    }

    &-title {
      color: var(--color-text-1);
      font-weight: 500;
      font-size: 24px;
      line-height: 32px;
    }

    &-sub-title {
      color: var(--color-text-3);
      font-size: 16px;
      line-height: 24px;
    }

    &-error-msg {
      height: 32px;
      color: rgb(var(--red-6));
      line-height: 32px;
    }

    &-password-actions {
      display: flex;
      justify-content: space-between;
    }
  }

  .captcha {
    height: 32px;
  }
</style>
